package com.sc.social.wechet.connect;

import com.sc.social.wechet.api.Wechet;
import org.springframework.social.ServiceProvider;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.support.OAuth2Connection;
import org.springframework.social.connect.support.OAuth2ConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2ServiceProvider;

/**
 * @author sc
 * Created on  2018/1/18
 */
public class WechetConnectionFactory extends OAuth2ConnectionFactory<Wechet> {


    public WechetConnectionFactory(String providerId, String appId, String appSecret) {
        super(providerId, new WechetServiceProvider(appId, appSecret), new WechetAdatper());
    }

    @Override
    protected String extractProviderUserId(AccessGrant accessGrant) {
        if(accessGrant instanceof WechetAccessGrant) {
            return ((WechetAccessGrant)accessGrant).getOpenId();
        }
        return null;
    }

    @Override
    public Connection<Wechet> createConnection(ConnectionData data) {
        return new OAuth2Connection<Wechet>(data, getMyServiceProvider(), getApiAdapter(data.getProviderUserId()));
    }

    @Override
    public Connection<Wechet> createConnection(AccessGrant accessGrant) {
        return new OAuth2Connection<Wechet>(getProviderId(), extractProviderUserId(accessGrant), accessGrant.getAccessToken(),
                accessGrant.getRefreshToken(), accessGrant.getExpireTime(), getMyServiceProvider(), getApiAdapter(extractProviderUserId(accessGrant)));
    }


    protected ApiAdapter<Wechet> getApiAdapter(String providerUserId) {
        return new WechetAdatper(providerUserId);
    }


    protected OAuth2ServiceProvider<Wechet> getMyServiceProvider() {
        return (OAuth2ServiceProvider<Wechet>)getServiceProvider();
    }
}
